package top.riske.animalhazardassessment.common.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;

import java.util.HashSet;
import java.util.Set;

/**
 * 账号权限枚举类
 * created by vital on 2025/3/1 下午3:15
 */
@Getter
public enum RoleEnum {

    ADMIN(0b0001,"管理员"),
    USER(0b0010,"普通用户"),
    ;

    @EnumValue
    public final int code;
    public final String description;

    RoleEnum(int code, String description) {
        this.code = code;
        this.description = description;
    }

    /**
     * 根据code获取枚举
     * @param code int类型的code
     * @return 枚举值，没有则返回null
     */
    public static RoleEnum getRoleEnumByCode(int code){
        for (RoleEnum roleEnum : RoleEnum.values()) {
            if (roleEnum.code == code) {
                return roleEnum;
            }
        }
        return null;
    }

    /**
     * 根据code获取角色描述
     * @param code int类型的code
     * @return 角色描述，没有则返回null
     */
    public static String getRoleDescriptionByCode(int code){
        for (RoleEnum roleEnum : RoleEnum.values()) {
            if (roleEnum.code == code) {
                return roleEnum.description;
            }
        }
        return null;
    }

    /**
     * 判断code是否包含某个角色权限
     */
    public static boolean isHavingRole(int code, RoleEnum roleEnum){
        return (code & roleEnum.code) == roleEnum.code;
    }

    /**
     *  根据code解析出对应的角色枚举
     */
    public static Set<RoleEnum> resolveRoleEnums(int code) {
        Set<RoleEnum> roles = new HashSet<>();
        for (RoleEnum role : RoleEnum.values()) {
            if ((code & role.code) == role.code) {
                roles.add(role);
            }
        }
        return roles;
    }

    /**
     * 根据角色枚举集合生成code
     * @param roles 角色枚举集合
     * @return code
     */
    public static int generateCode(Set<RoleEnum> roles) {
        return roles.stream().mapToInt(RoleEnum::getCode).reduce(0, (a, b) -> a | b);
    }


}
